package com.hua.utility.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilterBySpring extends org.springframework.web.filter.CharacterEncodingFilter {

    protected String encoding;

    @Override
    public void setEncoding(String encoding) {
        this.encoding = encoding;
        super.setEncoding(encoding);
        if (encoding == null) {
            encoding = "utf-8";
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if ("GET".equals(request.getMethod())) {
            super.doFilterInternal(new EncodeRequest(request), response, filterChain);
        } else {
            super.doFilterInternal(request, response, filterChain);
        }
    }

    class EncodeRequest extends HttpServletRequestWrapper {
        private final String[] charsets = { "iso8859-1", "gbk", "gb2312", "gb18030", "utf-8", "ucs" };

        @Override
        public String getParameter(String param) {
            String value = super.getParameter(param);
            return convertCharset(value);
        }

        private String convertCharset(String value) {
            String result = value;
            try {
                if (value != null) {
                    for (String charset : charsets) {
                        if (value.equals(new String(value.getBytes(charset), charset))) {
                            result = new String(value.getBytes(charset), encoding);
                            break;
                        }
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return result;
        }

        public EncodeRequest(HttpServletRequest request) {
            super(request);
            encoding = null;
        }
    }
}
